<template>
  <view class="webview-container">
    <web-view
      :src="wvSrc"
      ref="webview"
      :webview-styles="webviewStyles"
      :additional-http-headers="httpHeaders"
      @onPostMessage="handleMessage"
      @load="onWebviewLoad"
      @message="handleWebviewMessage"
    ></web-view>
  </view>
</template>

<script>
import globalConfig from '@/config';
import { getToken } from '@/utils/auth';
import { request, download } from '@/utils/request';
export default {
  data() {
    return {
      wvSrc: "",
      clientId: "",
      authToken: "",
      webviewRealWidth: 1200,
      screenWidth: 0,
      httpHeaders: {},
      webviewStyles: {
        progress: { color: '#FF3333' },
        // 关键修改：启用缩放配置
        scalable: true,               // 必须设为true
        zoom: true,                   // 明确启用缩放
        userScalable: true,           // 允许用户手势缩放
        scalesPageToFit: false,       // 禁用自动缩放
        // 设置合理的缩放范围
        minimumScale: 0.2,
        maximumScale: 5.0,
        // 其他配置保持不变
        allowsInlineMediaPlayback: true,
        gestureEnabled: true,
        multipleTouchEnabled: true
      }
    }
  },
  onLoad(options) {
    const systemInfo = uni.getSystemInfoSync();
    this.screenWidth = systemInfo.screenWidth;
    this.calculatedScale = this.screenWidth / this.webviewRealWidth;
    
    // 设置初始缩放比例
    this.webviewStyles.initialScale = this.calculatedScale;
    
    this.clientId = globalConfig.clientID || '';
    this.authToken = getToken() || '';
    console.log('token:', this.authToken);
    console.log('clientId:', this.clientId);

    // 设置 HTTP 请求头
    this.httpHeaders = {
      'Authorization': `Bearer ${this.authToken}`,
      'Client-Id': this.clientId,
      'Content-Type': 'application/json'
    };

    // 将认证信息添加到 URL 参数中（主要方案）
    this.wvSrc = `http://xxx.xxx.xxx:xx/process1?businessId=${options.businessId}&token=${this.authToken}&clientId=${this.clientId}`;
    this.createWebView();
  },
  onReady() {
    // setTimeout(() => {
    //   this.setCustomHeaders();
    //   this.enableZoom();  // 新增：启用缩放
    //   this.sendAuthToWebview(); // 发送认证信息到网页
    //   this.injectUniObject(); // 注入 uni 对象到 WebView
    //   this.setupPostMessageListener(); // 设置 postMessage 监听
    // }, 1500); // 延长延时确保 WebView 完全加载
  },
  methods: {
    createWebView() {
      let WEBID = 'webview_id';
      this.webId = WEBID;
      let that = this;
      const url = this.wvSrc
      const styles = {
        width: '200px',
        height: '500px'
      };
      that.dom = plus.webview.create(url, WEBID, styles);
      if (that.$root.$scope) {
        that.$root.$scope.$getAppWebview().append(this.dom);
      } else {
        getCurrentPages()[getCurrentPages().length - 1].$getAppWebview().append(that.dom);
      }
      plus.globalEvent.addEventListener('plusMessage', function (msg) {
        // console.log('//web传来的参数', msg.data.args.data) //web传来的参数
        const message = msg.data.args.data;
        if (message.name === 'postMessage') {
          // 处理下载逻辑
          // console.log('开始下载文件...');
          // console.log('info:', message.arg.info); 
          // console.log('ossId:',message.arg.info.ossId);
          // console.log('filename:',message.arg.info.originalName);
          const url = `/resource/oss/download/${message.arg.info.ossId}`;
          download(url,"",message.arg.info.originalName)
        }
      })
      console.log("创建WebView成功");
    },
    // 新增方法：启用平台特定的缩放
    enableZoom() {
      // 检查是否为 Android 平台
      if (uni.getSystemInfoSync().platform === 'android') {
        try {
          const currentWebview = this.$scope.$getAppWebview();
          const wv = currentWebview.children()[0];

          // 设置 webview 样式支持缩放
          wv.setStyle({
            scalable: true,
            zoom: true
          });

          // 使用 Android 原生 API 设置 WebView 缩放
          const WebSettings = plus.android.importClass("android.webkit.WebSettings");
          // 通过 plus.android.invoke 获取 settings
          const settings = plus.android.invoke(wv, "getSettings");

          // 启用缩放支持
          plus.android.invoke(settings, "setSupportZoom", true);
          plus.android.invoke(settings, "setBuiltInZoomControls", true);
          plus.android.invoke(settings, "setDisplayZoomControls", false); // 隐藏缩放控件
          plus.android.invoke(settings, "setUseWideViewPort", true);
          plus.android.invoke(settings, "setLoadWithOverviewMode", true);

          // 通过 evalJS 强制设置网页支持缩放
          setTimeout(() => {
            wv.evalJS(`
              (function() {
                console.log('开始设置网页缩放支持...');

                // 1. 移除现有的 viewport meta 标签
                var existingViewports = document.querySelectorAll('meta[name="viewport"]');
                existingViewports.forEach(function(viewport) {
                  viewport.remove();
                  console.log('移除了现有的 viewport 标签');
                });

                // 2. 添加支持缩放的 viewport
                var newViewport = document.createElement('meta');
                newViewport.name = 'viewport';
                newViewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=0.5, user-scalable=yes';
                document.head.appendChild(newViewport);
                console.log('已添加支持缩放的 viewport');

                // 3. 移除可能阻止缩放的 CSS
                var style = document.createElement('style');
                style.textContent = \`
                  * {
                    touch-action: manipulation !important;
                  }
                  html, body {
                    touch-action: manipulation !important;
                    -webkit-user-select: none;
                    -webkit-touch-callout: none;
                  }
                \`;
                document.head.appendChild(style);
                console.log('已添加支持缩放的 CSS');

                // 4. 检查最终的 viewport 设置
                var finalViewport = document.querySelector('meta[name="viewport"]');
                if (finalViewport) {
                  console.log('最终 viewport 内容:', finalViewport.content);
                } else {
                  console.log('警告: 未找到 viewport 标签');
                }

                console.log('网页缩放配置完成，请尝试双指缩放');

                // 5. 设置与 uni-app 的通信功能
                window.uniAppDownload = function(ossId, filename) {
                  console.log('准备发送下载请求到 uni-app:', { ossId, filename });

                  var message = {
                    type: 'download',
                    ossId: ossId,
                    filename: filename || 'attachment_' + ossId,
                    timestamp: Date.now()
                  };

                  try {
                    // 发送消息给 uni-app
                    if (window.parent && window.parent !== window) {
                      window.parent.postMessage(message, '*');
                      console.log('已通过 postMessage 发送下载请求');
                    }

                    // 如果有 uni 对象，也通过 uni.postMessage 发送
                    if (typeof uni !== 'undefined' && uni.postMessage) {
                      uni.postMessage({ data: message });
                      console.log('已通过 uni.postMessage 发送下载请求');
                    }

                    return true;
                  } catch (error) {
                    console.error('发送下载消息失败:', error);
                    return false;
                  }
                };

                console.log('uni-app 通信功能已设置');
                console.log('可用方法: window.uniAppDownload(ossId, filename)');
              })();
            `);
          }, 2000); // 延迟2秒确保页面完全加载

          console.log('Android WebView 缩放已启用');
        } catch (error) {
          console.error('启用 Android WebView 缩放失败:', error);
        }
      } else {
        console.log('非 Android 平台，跳过缩放设置');
      }
    },

    setCustomHeaders() {
      try {
        const currentWebview = this.$scope.$getAppWebview();
        const wv = currentWebview.children()[0];

        if (wv && this.authToken) {
          // 设置自定义请求头
          const headers = {
            'Authorization': `Bearer ${this.authToken}`,
            'Client-Id': this.clientId,
            'Content-Type': 'application/json'
          };

          console.log('设置 WebView 请求头:', headers);

          // 使用 setStyle 方法设置请求头
          wv.setStyle({
            additionalHttpHeaders: headers
          });

          console.log('WebView 请求头设置完成');

          // 或者使用 evalJS 在网页中设置
          wv.evalJS(`
            // 在网页中设置认证信息到 localStorage
            localStorage.setItem('authToken', '${this.authToken}');
            localStorage.setItem('clientId', '${this.clientId}');

            // 重写 fetch 和 XMLHttpRequest 以自动添加认证头
            const originalFetch = window.fetch;
            window.fetch = function(url, options = {}) {
              options.headers = options.headers || {};
              options.headers['Authorization'] = 'Bearer ${this.authToken}';
              options.headers['Client-Id'] = '${this.clientId}';
              return originalFetch(url, options);
            };
          `);
        }
      } catch (error) {
        console.error('设置 WebView 请求头失败:', error);
      }
    },

    // 发送认证信息到网页
    sendAuthToWebview() {
      try {
        const currentWebview = this.$scope.$getAppWebview();
        const wv = currentWebview.children()[0];

        if (wv && this.authToken) {
          console.log('向网页发送认证信息:', {
            authToken: this.authToken,
            clientId: this.clientId
          });

          // 通过 evalJS 在网页中设置认证信息
          const authToken = this.authToken;
          const clientId = this.clientId;

          wv.evalJS(`
            (function() {
              console.log('接收到认证信息，开始设置...');

              // 立即设置到 localStorage 和 sessionStorage
              try {
                localStorage.setItem('authToken', '` + authToken + `');
                localStorage.setItem('clientId', '` + clientId + `');
                sessionStorage.setItem('authToken', '` + authToken + `');
                sessionStorage.setItem('clientId', '` + clientId + `');
                console.log('存储设置完成');
              } catch(e) {
                console.error('存储设置失败:', e);
              }

              // 设置全局变量
              window.authToken = '` + authToken + `';
              window.clientId = '` + clientId + `';

              // 如果页面已经有 axios，重写其默认配置
              if (window.axios) {
                window.axios.defaults.headers.common['Authorization'] = 'Bearer ` + authToken + `';
                window.axios.defaults.headers.common['Client-Id'] = '` + clientId + `';
                console.log('Axios 默认头设置完成');
              }

              // 重写 fetch 方法
              if (window.fetch && !window.fetch._rewritten) {
                const originalFetch = window.fetch;
                window.fetch = function(url, options = {}) {
                  options.headers = options.headers || {};
                  if (!options.headers['Authorization']) {
                    options.headers['Authorization'] = 'Bearer ` + authToken + `';
                  }
                  if (!options.headers['Client-Id']) {
                    options.headers['Client-Id'] = '` + clientId + `';
                  }
                  console.log('Fetch 请求:', url, options.headers);
                  return originalFetch(url, options);
                };
                window.fetch._rewritten = true;
                console.log('Fetch 重写完成');
              }

              // 重写 XMLHttpRequest
              if (window.XMLHttpRequest && !window.XMLHttpRequest._rewritten) {
                const originalXHR = window.XMLHttpRequest;
                window.XMLHttpRequest = function() {
                  const xhr = new originalXHR();
                  const originalSend = xhr.send;

                  xhr.send = function(data) {
                    if (!this.getResponseHeader || !this.getResponseHeader('Authorization')) {
                      this.setRequestHeader('Authorization', 'Bearer ` + authToken + `');
                      this.setRequestHeader('Client-Id', '` + clientId + `');
                      console.log('XHR 请求头已设置');
                    }
                    return originalSend.apply(this, arguments);
                  };

                  return xhr;
                };
                window.XMLHttpRequest._rewritten = true;
                console.log('XMLHttpRequest 重写完成');
              }

              console.log('认证信息设置完成，当前 token:', window.authToken ? '已设置' : '未设置');

              // 设置请求代理函数
              window.apiRequest = function(url, options = {}) {
                return new Promise((resolve, reject) => {
                  const requestId = 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

                  // 设置响应处理函数
                  window.handleApiResponse = function(id, data) {
                    if (id === requestId) {
                      resolve(data);
                      delete window.handleApiResponse;
                      delete window.handleApiError;
                    }
                  };

                  window.handleApiError = function(id, error) {
                    if (id === requestId) {
                      reject(error);
                      delete window.handleApiResponse;
                      delete window.handleApiError;
                    }
                  };

                  // 发送消息到 uni-app
                  if (window.uni && window.uni.postMessage) {
                    window.uni.postMessage({
                      data: {
                        type: 'API_REQUEST',
                        url: url,
                        method: options.method || 'GET',
                        data: options.data,
                        requestId: requestId
                      }
                    });
                  } else {
                    reject(new Error('uni.postMessage 不可用'));
                  }
                });
              };

              console.log('API 代理函数设置完成');

              // 不再自动刷新页面，让页面使用代理函数
            })();
          `);
        }
      } catch (error) {
        console.error('发送认证信息到网页失败:', error);
      }
    },

    // 网页加载完成时的回调
    onWebviewLoad(e) {
      console.log('网页加载完成:', e);
      // 延迟发送认证信息，确保网页完全加载
      setTimeout(() => {
        this.sendAuthToWebview();
      }, 500);
    },

    // 处理 API 请求代理
    async handleApiRequest(message) {
      try {
        const { url, method = 'GET', data, requestId } = message;

        console.log('代理 API 请求:', { url, method, data });

        // 使用 uni.request 发送请求，自动携带认证信息
        const response = await uni.request({
          url: url,
          method: method,
          data: data,
          header: {
            'Authorization': `Bearer ${this.authToken}`,
            'Client-Id': this.clientId,
            'Content-Type': 'application/json'
          }
        });

        console.log('API 请求响应:', response);

        // 将响应发送回网页
        const currentWebview = this.$scope.$getAppWebview();
        const wv = currentWebview.children()[0];

        wv.evalJS(`
          if (window.handleApiResponse) {
            window.handleApiResponse('${requestId}', ${JSON.stringify(response.data)});
          }
        `);

      } catch (error) {
        console.error('API 请求失败:', error);

        // 发送错误信息回网页
        const currentWebview = this.$scope.$getAppWebview();
        const wv = currentWebview.children()[0];

        wv.evalJS(`
          if (window.handleApiError) {
            window.handleApiError('${message.requestId}', ${JSON.stringify(error)});
          }
        `);
      }
    }
  }
}
</script>